<template>
<div class="menuManage">
  <div class="menu-left">
    <div class="menu-tree-oper">
      <i
        class="el-icon-circle-plus"
        v-if="currentData && (!currentData.menuType || currentData.menuType === '0')"
        @click="() => addNode()"></i>
      <template v-if="currentData && currentData.id !== '_ROOT_'">
        <i class="el-icon-edit" @click="() => editNode()"></i>
        <el-popconfirm
          :title="`是否确认删除【${currentData.menuName}】？`"
          @confirm="deleteNode">
          <i slot="reference" class="el-icon-delete"></i>
        </el-popconfirm>
      </template>
    </div>
    <el-tree
      ref="tree"
      highlight-current
      node-key="id"
      @node-click="nodeClick"
      :data="treeData"
      :props="{ label: 'menuName', children: 'children' }"></el-tree>
    <y-form
      v-model="forms.formModel"
      :visible.sync="showForm"
      :title="formTypeTitle[forms.formType]"
      destroy-on-close
      width="50%"
      :form-attrs="formAttrs"
      :columns="formColumns"
      @ensure="ensureModel">
      <template slot="menuIcon">
        <e-icon-picker v-model="forms.formModel.menuIcon"/>
      </template>
    </y-form>
  </div>
  <div class="menu-right">
    <y-table
      border
      :get-data-way="{ data: tableData }"
      :columns="tableColumns">
      <el-table-column slot="menuIcon" label="图标" align="center" header-align="center">
        <template v-slot="scope">
          <i :class="scope.row.menuIcon"></i>
        </template>
      </el-table-column>
      <el-table-column slot="status" label="是否启用" align="center" header-align="center">
        <template v-slot="scope">
          <el-popconfirm
            :title="scope.row.status === '0' ? `是否确认禁用【${scope.row.menuName}】？` : `是否确认启用【${scope.row.menuName}】？`"
            @confirm="() => {
            if(scope.row.status === '0') lockMenu(scope.row)
            else unlockMenu(scope.row);
          }"
          >
            <el-switch
                disabled
                slot="reference"
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"></el-switch>
          </el-popconfirm>
        </template>
      </el-table-column>
      <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="140">
        <template v-slot="scope">
          <div class="table-buttons">
            <el-button type="primary" size="mini" @click="editNode(scope.row)">编辑</el-button>
            <el-popconfirm
              :title="`是否确认删除【${scope.row.menuName}】？`"
              @confirm="deleteNode(scope.row)">
              <el-button slot="reference" type="danger" size="mini">删除</el-button>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </y-table>
  </div>
</div>
</template>

<script>
const formTypeTitle = {
  'ADD': '添加菜单',
  'EDIT': '编辑菜单',
  'VIEW': '预览菜单',
}
export default {
  name: "menuManage",
  computed:{
    formColumns(){
      if(!this.currentData) return [];
      let opt = [
        { label: '目录', value: '0' },
        { label: '菜单', value: '1' },
        { label: '按钮', value: '2' }
      ];
      let options = opt;
      if(this.forms.formType === 'ADD'){
        switch (this.currentData.menuType){
          case '0':case undefined:{ //目录
            options = opt.slice(0,2);
            break;
          }
          case '1':{ //菜单
            options = opt.slice(2);
            break;
          }
          default:{
            options = [];
            break;
          }
        }
      }
      return [{
        label: "菜单名称",
        prop: "menuName",
        comp:{
          compType: 'input',
          attrs:{
            maxlength: 30,
            showWordLimit: true
          }
        }
      },{
        label: "菜单类型",
        prop: "menuType",
        comp:{
          compType: 'select',
          options,
          attrs:{
            clearable: true,
            disabled: this.forms.formType === 'EDIT'
          },
          listeners:{
            change: (function(val){
              if(val !== '1'){//菜单
                this.forms.formModel.menuRouter = '';
                //this.formAttrs.rules.menuRouter = [{required: true, message: "请输入菜单路由", trigger: "blur"}]
              }else{
                //delete this.formAttrs.rules.menuRouter;
              }
            }).bind(this)
          }
        }
      },{
        label: "上级菜单",
        prop: "menuPName",
        comp:{
          compType: 'input',
          attrs:{
            disabled: true
          }
        }
      },{
        label: "菜单路由",
        prop: "menuRouter",
        comp:{
          compType: 'input',
          attrs:{
            clearable: true,
            disabled: this.forms.formModel.menuType !== '1'
          }
        }
      },{
        label: "排序",
        prop: "orderNum",
        comp:{
          compType: 'input-number',
        }
      },{
        label: "图标",
        prop: "menuIcon",
        template: true
      },{
        label: "备注",
        prop: "remarks",
        comp:{
          compType: 'input',
          attrs:{
            type: 'textarea',
            maxlength: '100',
            showWordLimit: true
          }
        }
      },{
        label: "是否启用",
        prop: "status",
        comp:{
          compType: 'switch',
          attrs:{
            activeValue: '0',
            inactiveValue: '1'
          }
        }
      }];
    }
  },
  data(){
    return{
      formTypeTitle,
      treeData: [{
        id: '_ROOT_',
        menuName: '菜单管理',
      }],
      currentData: null,
      $tree: null,
      forms:{
        formType: '', //ADD, EDIT, VIEW
        formModel:{ //currentForm的一个拷贝，绑定弹出框model用
          menuType: '',
          menuName: '',
          menuPid: '',
          menuPName: '',
          menuRouter: '',
          orderNum: '',
          menuIcon: '',
          remarks: '',
          status: '0'
        },
        //当前展示的节点实体
        currentForm: null
      },
      showForm: false,
      formAttrs:{
        labelWidth: '100px',
        rules: {
          menuName: [{required: true, message: "请输入菜单名", trigger: "blur"}],
          menuType: [{required: true, message: "请选择菜单类型", trigger: "change"}],
          menuIcon: [{required: true, message: "请选择图标", trigger: "change"}]
        }
      },
      tableData: [],
      tableColumns: [{
        label: "菜单名称",
        prop: "menuName"
      },{
        label: "菜单类型",
        prop: "menuType",
        formatter(row) {
          let opt = [
            { label: '目录', value: '0' },
            { label: '菜单', value: '1' },
            { label: '按钮', value: '2' }
          ];
          return opt.find(o => o.value === row.menuType).label;
        }
      },{
        label: "菜单路由",
        prop: "menuRouter"
      },{
        label: "排序",
        prop: "orderNum"
      },{
        label: "图标",
        prop: "menuIcon",
        template: true
      },{
        label: "备注",
        prop: "remarks"
      },{
        label: "是否启用",
        prop: "status",
        template: true
      }]
    }
  },
  mounted(){
    this.$yAxios({
      url: this.$api.system.queryMenuTreeNoStatus
    }, info => {
      if(info && Array.isArray(info)){
        this.$set(this.treeData[0], 'children', info);
        this.$tree = this.$refs['tree'];
        this.focusRoot();
      }
    })
  },
  methods:{
    focusRoot(){
      if(this.$tree){
        this.$tree.setCurrentKey('_ROOT_');
        this.$set(this, 'currentData', this.treeData[0]);
        this.$tree.getNode('_ROOT_').expanded = true;
      }
    },
    getNodeNameById(id){
      return this.$tree.getNode(id).data.menuName;
    },
    editNode(data = this.currentData){
      this.forms.currentForm = data;
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = this.forms.currentForm[key];
      });
      if(data.id !== '_ROOT_'){
        if(!this.forms.currentForm.menuPName){
          if(!this.forms.formModel.menuPid) this.forms.formModel.menuPid = '_ROOT_';
          this.forms.formModel.menuPName = this.getNodeNameById(this.forms.formModel.menuPid)
        }
      }
      this.forms.formType = 'EDIT';
      this.$nextTick(() => {
        this.showForm = true;
      })
    },
    deleteNode(data = this.currentData){
      if(!data || data.id === '_ROOT_'){
        this.$alert('请点选要删除的节点', {
          confirmButtonText: '确定'
        });
        return;
      }
      if(data.children && data.children.length){
        this.$alert('无法删除包含子节点的菜单', {
          confirmButtonText: '确定'
        });
        return;
      }
      this.$yAxios({
        data: {
          id: data.id
        },
        url: this.$api.system.removeMenuById,
        loading: true
      }, info => {
        let pId = data.menuPid || '_ROOT_';
        let PNode = this.$tree.getNode(pId);
        let pArray = PNode.data.children;
        if(pArray){
          let index = pArray.indexOf(data);
          if(index >= 0){
            this.$delete(pArray, index);
            if(data === this.currentData){
              this.$tree.setCurrentKey(pId);
              this.currentData = PNode.data;
            }
          }
        }
        this.$message({
          type: 'success',
          message: '删除成功'
        });
      })
    },
    nodeClick(data){
      this.currentData = data;
    },
    resetForm(){
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = key === 'status' ? '0' : "";
      })
    },
    addNode(data = this.currentData){
      this.resetForm();
      if(data.id !== '_ROOT_'){
        this.forms.formModel.menuPid = data.id;
      }
      this.forms.formModel.menuPName = data.menuName;
      this.forms.formType = 'ADD';
      this.$nextTick(() => {
        this.showForm = true;
      })
    },
    ensureModel(form){
      /*if(this.currentData.menuPid === ''){
        form['menuPid'] = '';
        form['menuPName'] = '';
      }*/
      let newForm;
      if(this.forms.formType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = Object.assign({}, form);
      }
      if(newForm.menuPid === '_ROOT_') newForm.menuPid = '';
      this.$yAxios({
        data: newForm,
        url: this.$api.system.saveOrUpdateMenu,
        loading: true
      }, info => {
        newForm = info;
        if(!newForm.menuPid) {
          newForm.menuPid = '_ROOT_';
          newForm.menuPName = '菜单管理';
        }
        switch(this.forms.formType){
          case 'ADD':{
            if(!this.currentData.children){
              this.$set(this.currentData, 'children', []);
            }
            this.currentData.children.push(newForm);
            this.$tree.getNode(this.currentData).expanded = true;
            this.tableData = this.currentData.children;
            break;
          }
          case 'EDIT':{
            Object.assign(this.forms.currentForm, newForm);
            break;
          }
        }
        this.showForm = false;
        this.$message({
          type: 'success',
          message: '保存成功'
        });
      })
    },
    lockMenu(row){
      this.$yAxios({
        url: this.$api.system.lockMenu,
        data: {
          ids: [row.id]
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功禁用菜单【${row.menuName}】`
        });
        row.status = '1';
      })
    },
    unlockMenu(row){
      this.$yAxios({
        url: this.$api.system.unlockMenu,
        data: {
          ids: [row.id]
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功启用用菜单【${row.menuName}】`
        });
        row.status = '0';
      })
    }
  },
  watch:{
    'currentData'(val){
      if(!val || !val.children) this.tableData = [];
      this.tableData = val.children;
    }
  }
}
</script>

<style scoped lang="less">
.menuManage{
  display: flex;
  height: 100%;
  width: 100%;
  >.menu-left{
    display: inline-block;
    min-width: 200px;
    flex-shrink: 0;
    >.menu-tree-oper{
      display: flex;
      align-items: center;
      justify-content: flex-end;
      height: 50px;
      border-bottom: @common-dashed-border;
      i{
        padding: 0 10px;
        cursor: pointer;
        color: @common-color;
      }
    }
    >.el-tree{
      height: calc(100% - 50px);
      overflow-y: auto;
    }
  }
  >.menu-right{
    flex-grow: 2;
    overflow: auto;
  }
}
</style>